package com.xzy.wificar;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.SurfaceTexture;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.Formatter;
import android.util.Log;
import android.view.MotionEvent;


import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;


import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;


public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnTouchListener  , VLCPlayer.VLCPlayerCallback {

    private ImageView surfaceView;

    private static String SERVER_URL = "http://192.168.4.1:80/"; // 替换为实际的服务器 IP 地址,就是小车的wifi ip地址
    private static String STREAM_URL = "http://192.168.4.1:81/"; // 视频流地址

    private Button forwardButton; //前
    private Button backwardButton; //后
    private Button leftButton; //左
    private Button rightButton; //右

    private Button connectionStatusIndicator;
    private TextView connectionStatusTextView;
    private TextView setting;
    private Switch ledSwitch;

    private TextureView textureView;

    private VLCPlayer vlcPlayer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        connectionStatusIndicator=findViewById(R.id.connection_status_indicator);
        connectionStatusTextView=findViewById(R.id.connection_status_text);
        //获取网关地址
//        getServerIp();
        //测试连接服务器成功
        //每5秒钟测试一次连接
        connectHandler.post(connectRunnable);
        //视频展示
        surfaceView = findViewById(R.id.surface_view);


        new StreamTask().execute();
        //遥控
        forwardButton = findViewById(R.id.forwardButton);
        forwardButton.setOnTouchListener(this);
        backwardButton = findViewById(R.id.backwardButton);
        backwardButton.setOnTouchListener(this);
        leftButton = findViewById(R.id.leftButton);
        leftButton.setOnTouchListener(this);
        rightButton = findViewById(R.id.rightButton);
        rightButton.setOnTouchListener(this);

        setting=findViewById(R.id.setting);
        setting.setOnClickListener(this);
        ledSwitch=findViewById(R.id.led);
        ledSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ledSwitch.isChecked()){
                    sendHttpCommand("cmd/open");
                }else {
                    sendHttpCommand("cmd/close");
                }
            }
        });
        textureView=findViewById(R.id.video_view);
        textureView.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
                initVLCPlayer();
            }

            @Override
            public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {

            }

            @Override
            public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {

            }
        });


    }
    private void initVLCPlayer() {
        vlcPlayer = new VLCPlayer(this);
        vlcPlayer.setVideoSurface(textureView);
        vlcPlayer.setDataSource(STREAM_URL+"stream");
        vlcPlayer.setCallback(this);
        vlcPlayer.play();
    }




    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v == forwardButton) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                sendHttpCommand("cmd/qianjin");
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                sendHttpCommand("cmd/tingzhi");
            }
        } else if (v == backwardButton) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                sendHttpCommand("cmd/houtui");
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                sendHttpCommand("cmd/tingzhi");
            }
        } else if (v == leftButton) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                sendHttpCommand("cmd/zuozhuan");
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                sendHttpCommand("cmd/tingzhi");
            }
        } else if (v == rightButton) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                sendHttpCommand("cmd/youzhuan");
            }
            if (event.getAction() == MotionEvent.ACTION_UP) {
                sendHttpCommand("cmd/tingzhi");
            }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        if (v==setting){
            //这里弹出设备ip和网关地址
            //安卓获取本机wifi网关
            WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            String ipAddress = Formatter.formatIpAddress(wifiManager.getDhcpInfo().gateway);
            //提示
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("设置")
                    .setMessage("服务地址："+ipAddress)
                    .setPositiveButton("确定", null)
                    .show();
        }
    }

    @Override
    public void onBuffering(float bufferPercent) {

    }

    @Override
    public void onEndReached() {

    }

    @Override
    public void onError() {

    }

    @Override
    public void onTimeChanged(long currentTime) {

    }

    @Override
    public void onPositionChanged(float position) {

    }


    private class StreamTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(STREAM_URL+"jpeg")
                    .build();

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.e("StreamTask", "Error fetching stream: " + e.getMessage());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    Log.i("test", response.isSuccessful() + "");
                    if (response.isSuccessful()) {
                        ResponseBody body = response.body();
                        if (body != null) {
                            InputStream inputStream = body.byteStream();
                            try {
                                handleImageData(inputStream);
                            } catch (IOException e) {
                                Log.e("StreamTask", "Error handling image data: " + e.getMessage());
                            }
                        }
                    }
                }
            });
            return null;
        }

        private void handleImageData(InputStream inputStream) throws IOException {
            byte[] buffer = new byte[4096];
            int bytesRead;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
                if (isJpegEnd(buffer, bytesRead)) {
                    byte[] imageBytes = baos.toByteArray();
                    final Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
//                    Log.i("iiiiiiiiiii", bitmap.getHeight() + " " + bitmap.getWidth());

                    runOnUiThread(() -> surfaceView.setImageBitmap(bitmap));
                    baos.reset();
                }
            }
        }

        private boolean isJpegEnd(byte[] buffer, int bytesRead) {
            // 简单检查是否到达 JPEG 数据的结束部分，可根据实际情况调整
            for (int i = 0; i < bytesRead; i++) {
                if (buffer[i] == (byte) 0xFF && buffer[i + 1] == (byte) 0xD9) {
                    return true;
                }
            }
            return false;
        }
    }

//发送控制命令
    private void sendHttpCommand(String command) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(SERVER_URL + command)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("sendHttpCommand", "Error fetching stream: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {

                }
            }
        });
    }


    Handler connectHandler=new Handler();
    Runnable connectRunnable=new Runnable() {
        @Override
        public void run() {
            connectStatus();
            connectHandler.postDelayed(connectRunnable,5000);
        }
    };

    //获取连接状态
    private void connectStatus() {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(SERVER_URL)
                .build();
        //设置请求超时时间
        client.newBuilder().connectTimeout(1, TimeUnit.SECONDS);
        client.newBuilder().readTimeout(1, TimeUnit.SECONDS);
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("StreamTask", "Error fetching stream: " + e.getMessage());
                //修改状态
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 修改状态
                        connectionStatusIndicator.setBackground(getDrawable(R.drawable.red_dot) );
                        connectionStatusTextView.setText(R.string.notConnect);
                        connectionStatusTextView.setTextColor(getResources().getColor(R.color.red));
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    //修改状态
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            // 修改状态
                            connectionStatusIndicator.setBackground(getDrawable(R.drawable.green_dot) );
                            connectionStatusTextView.setText(R.string.connected);
                            connectionStatusTextView.setTextColor(getResources().getColor(R.color.green));
                        }
                    });
                }
            }
        });
    }

}